package org.bycloud.web.auth;

import java.util.List;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.bycloud.api.auth.ResourceService;
import org.bycloud.common.Result;
import org.bycloud.common.TreeNode;
import org.bycloud.common.model.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/resource")
public class ResourceController {

	private String getNode(String node) {
		return StringUtils.equals(node, "root") ? "0" : node;
	}

	@Autowired
	ResourceService resourceService;

	@ResponseBody
	@RequestMapping("/tree")
	public List<Resource> treeGrid(String node) {
		return resourceService.findChildren(getNode(node));
	}

	@ResponseBody
	@RequestMapping("/role")
	public List<TreeNode> treeSelectChecked(String node,
			@RequestParam(required = false, value = "checked") Boolean checked) {
		return resourceService.findTreeNodes(getNode(node), checked == null ? false : true);
	}

	@ResponseBody
	@RequestMapping("/save")
	public Result save(Resource resource) {
		resourceService.save(resource);
		return Result.success("操作成功.");
	}
	
	
	@ResponseBody
	@RequestMapping("/permissions")
	public Set<String> findRoleResources(String resourceId) {
		Set<String> ret = resourceService.findPermissionIds(resourceId);
		return ret;
	}
}
